//
//  OrderSumupViewController.swift
//  AutoPrint
//
//  Created by 胡玉葱 on 16/12/4.
//  Copyright © 2016年 fatcat. All rights reserved.
//

import UIKit

class OrderSumupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PayViewControllerDelegate {

    var step0VC: UIViewController?
    
    var shopInfos: NSArray!
    var fileInfos: NSArray!
    
    var tableView: UITableView!
    
    var bottomBar: UIView! // 底部栏
    var totalPriceLabel: UILabel! // 合计label
    var submitBtn: UIButton! // 提交订单按钮
    
    var spinner: UIView!
    var actIndi: UIActivityIndicatorView!
    
    var totalPrice: Double = 0.0
    
    var shopDescriptionHeight:CGFloat = 72.0 //商家详细描述的高度
    
    var commentInput:UITextField! // 备注输入框
    
    var pricesTabel: NSDictionary!
    
    var allDescribe = ""
    
    var phoneInput: UITextField!
    var nameInput: UITextField!
    
    convenience init(files: NSArray, shopInfo: NSArray){
        self.init()
        fileInfos = files
        shopInfos = shopInfo
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "提交订单"
        let shopItem = shopInfos.objectAtIndex(0) as! NSDictionary
        let describe = shopItem.objectForKey("description") as? String
        let address = shopItem.objectForKey("location") as? String
        let phone = shopItem.objectForKey("phone") as? String
        let startTime = shopItem.objectForKey("start_time") as? String
        let endTime = shopItem.objectForKey("end_time") as? String
        
        
        
        if address != nil {
            allDescribe += "地址: \(address!)\n"
        }
        
        if phone != nil{
            allDescribe += "电话: \(phone!)\n"
        }
        
        if startTime != nil && endTime != nil{
            allDescribe += "营业时间: \(startTime!)~\(endTime!)\n"
        }else if startTime != nil{
            allDescribe += "营业时间: \(startTime!)开始\n"
        }else if endTime != nil{
            allDescribe += "营业时间: \(endTime!)打烊\n"
        }
        
        
        
        // MARK: 备注输入框
        commentInput = UITextField(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32, height: 28))
        commentInput.tag = 101
        commentInput.placeholder = "留下你的备注，比如装订等等"
        commentInput.addTarget(self, action: #selector(OrderSumupViewController.textFieldScrollUp(_:)), forControlEvents: .EditingDidBegin)
        
        tableView = UITableView(frame: view.frame, style: .Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .None
        tableView.allowsSelection = false
        tableView.keyboardDismissMode = .OnDrag
        view.addSubview(tableView)
        
        
        
        // MARK: 底部栏
        bottomBar = UIView(frame: CGRect(x: -0.5, y: view.bounds.height - 48, width: view.bounds.width+1, height: 48))
        bottomBar.backgroundColor = UIColor.whiteColor()
        bottomBar.layer.borderColor = UIColor.lightGrayColor().CGColor
        bottomBar.layer.borderWidth = 0.5
        view.addSubview(bottomBar)
        
        // MARK: 底部显示合计
        totalPriceLabel = UILabel(frame: CGRect(x: 16, y: 8, width: 120, height: 32))
        totalPriceLabel.font = UIFont.systemFontOfSize(12)
        bottomBar.addSubview(totalPriceLabel)
        
        //MARK: 计算合计
        
        let pricesModel = shopInfos.objectAtIndex(1) as! NSDictionary
        let prices = NSMutableDictionary()
        for item in pricesModel.allValues{
            let priceItem = item as! NSDictionary
            let paperSize = priceItem.objectForKey("paper_type") as! String
            let paperPrice = priceItem.objectForKey("price") as! String
            
            prices.setValue(paperPrice, forKey: paperSize)
            
        }
        print(prices)
        pricesTabel = NSDictionary(dictionary: prices)
        
        
        // TODO: 获取价目
        var singleBW:Double?
        let singleBWStr = prices.objectForKey("1")
        if singleBWStr != nil{
            allDescribe += "单面黑白: ￥\(singleBWStr as! String)  "
            singleBW = Double(singleBWStr as! String)
        }
        var duplexBW:Double?
        let duplexBWStr = prices.objectForKey("2")
        if duplexBWStr != nil{
            allDescribe += "双面黑白: ￥\(duplexBWStr as! String)  "
            duplexBW = Double(duplexBWStr as! String)
        }
        var singleColor:Double?
        let singleColorStr = prices.objectForKey("3")
        if singleColorStr != nil{
            allDescribe += "单面彩色: ￥\(singleColorStr as! String)  "
            singleColor = Double(singleColorStr as! String)
        }
        
        var duplexColor:Double?
        let duplexColorStr = prices.objectForKey("4")
        if duplexColorStr != nil{
            allDescribe += "双面彩色: ￥\(duplexColorStr as! String)  "
            duplexColor = Double(duplexColorStr as! String)
        }
        
        if describe != nil{
            allDescribe += "\n\(describe!)"
        }
        
        shopDescriptionHeight = allDescribe.boundingRectWithSize(CGSize(width: view.bounds.width - 32, height: CGFloat(MAXFLOAT)), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(14)], context: nil).height
        
        totalPrice = 0.0
        for item in fileInfos{
            let fileItem = item as! NSDictionary
            let pageNum = fileItem.objectForKey("page_number") as! Int
            let quantity = fileItem.objectForKey("goods_number") as! Int
            
            
            let bwOption = fileItem.objectForKey("black_white_color") as! Int
            let duplex = fileItem.objectForKey("single_double") as! Int
            
            if duplex == 1 && bwOption == 1{
                if singleBW != nil{
                    totalPrice += Double(pageNum*quantity)*singleBW!
                }
            }else if duplex == 1 && bwOption == 2{
                if singleColor != nil{
                    totalPrice += Double(pageNum*quantity)*singleColor!
                }
            }else if duplex == 2 && bwOption == 1{
                if duplexBW != nil{
                    totalPrice += Double(pageNum*quantity)*duplexBW!
                }
            }else if duplex == 2 && bwOption == 2{
                if duplexColor != nil{
                    totalPrice += Double(pageNum*quantity)*duplexColor!
                }
            }
        }
        let showStr = "合计: ￥\(String(format: "%.2lf", totalPrice))"
        let attrStr = NSMutableAttributedString(string: showStr)
        if Int(totalPrice*100) != 0{
            attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor(), range: NSMakeRange(4, attrStr.length - 4))
        }
        
        attrStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(16), range: NSMakeRange(5, attrStr.length - 5))
        
        totalPriceLabel.attributedText = attrStr
        
        // MARK:提交按钮
        submitBtn = UIButton(frame: CGRect(x: view.bounds.width - 119, y: 0, width: 120, height: 48))
        submitBtn.backgroundColor = UIColor.orangeColor()
        submitBtn.setTitle("下一步", forState: .Normal)
        submitBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        bottomBar.addSubview(submitBtn)
        submitBtn.addTarget(self, action: #selector(OrderSumupViewController.nextStep), forControlEvents: .TouchUpInside)
        
        
        
        //菊花
        spinner = UIView(frame: view.frame)
        let actIndiBG = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        actIndiBG.center = view.center
        actIndiBG.backgroundColor = UIColor(white: 0, alpha: 0.7)
        actIndiBG.layer.cornerRadius = 8
        spinner.addSubview(actIndiBG)
        actIndi = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
        actIndi.startAnimating()
        actIndi.center = view.center
        spinner.addSubview(actIndi)
        view.addSubview(spinner)
        
        spinner.alpha = 0
        
        
        nameInput = UITextField(frame: CGRect(x: 16, y: 8, width: 100, height: 28))
        nameInput.placeholder = "姓名"
        nameInput.tag = 102
        
        phoneInput = UITextField(frame: CGRect(x: 124, y: 8, width: view.bounds.width - 124 - 16, height: 28))
        phoneInput.placeholder = "联系电话"
        phoneInput.keyboardType = .PhonePad
        phoneInput.textAlignment = .Right
        phoneInput.tag = 104
        
        if NSUserDefaults.standardUserDefaults().objectForKey("info_name") != nil{
            nameInput.text = NSUserDefaults.standardUserDefaults().objectForKey("info_name") as? String
        }
        
        if NSUserDefaults.standardUserDefaults().objectForKey("info_phone") != nil {
            phoneInput.text = NSUserDefaults.standardUserDefaults().objectForKey("info_phone") as? String
        }
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 2
        case 3:
            return fileInfos.count*2+2
        default:
            return 1
        }
    }
    
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch section {
        case 1:
            return "您的信息"
        case 2:
            return "备注"
        case 3:
            return "合计"
        default:
            return nil
        }
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0.001
        }
        return 16
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                return 44
            case 1:
                return shopDescriptionHeight + 16 // 动态调整
            default:
                return 44
            }
        case 3:
            return 30
        default:
            return 44
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "item")
        let shopItem = shopInfos.objectAtIndex(0) as! NSDictionary
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                let icon = UIImageView(frame: CGRect(x: 16, y: 8, width: 28, height: 28))
                icon.backgroundColor = UIColor.grayColor()
                cell.addSubview(icon)
                
                let namLabel = UILabel(frame: CGRect(x: 52, y: 8, width: view.bounds.width - 60, height: 28))
                namLabel.text = shopItem.objectForKey("nickname") as? String
                cell.addSubview(namLabel)
                
                let shopImage = shopItem.objectForKey("logo") as? String
                if shopImage != nil{
                    let imageURL = NSURL(string: shopImage!)
                    if imageURL != nil{
                        NSURLSession.sharedSession().dataTaskWithURL(imageURL!, completionHandler: { (data:NSData?, resp:NSURLResponse?, err:NSError?) in
                            if err == nil{
                                if data != nil{
                                    let image = UIImage(data: data!)
                                    icon.image = image
                                }
                            }
                        })
                    }
                }
                break
            case 1:
                
                // TODO: 加一行 显示营业时间； 再加一到两行显示价目
                let describeLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32, height: shopDescriptionHeight))
                describeLabel.textColor = UIColor.grayColor()
                describeLabel.font = UIFont.systemFontOfSize(14)
                describeLabel.numberOfLines = 0
                cell.addSubview(describeLabel)
                
                describeLabel.text = allDescribe
                break
            default:
                break
            }
            
            break
        case 1:
            cell.addSubview(nameInput)
            cell.addSubview(phoneInput)
            let seper = UIView(frame: CGRect(x: 124, y: 0, width: 1, height: 44))
            seper.backgroundColor = UIColor.lightGrayColor()
            cell.addSubview(seper)
            break
        case 2:
            cell.addSubview(commentInput)
            break
        case 3:
            let infoLabel = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32 - 96, height: 16))
            infoLabel.font = UIFont.systemFontOfSize(14)
            cell.addSubview(infoLabel)
            
            let priceLabel = UILabel(frame: CGRect(x: view.bounds.width - 88, y: 8, width: 80, height: 16))
            priceLabel.font = UIFont.systemFontOfSize(14)
            priceLabel.textAlignment = .Right
            priceLabel.textColor = UIColor.lightGrayColor()
            cell.addSubview(priceLabel)
            
            priceLabel.text = "￥ 0"
            
            if indexPath.row/2 < fileInfos!.count{
                let fileItem = fileInfos?.objectAtIndex(indexPath.row/2) as! NSDictionary
                if indexPath.row % 2 == 0{
                    infoLabel.text = fileItem.objectForKey("file_name") as? String
                    priceLabel.alpha = 0
                }else if indexPath.row % 2 == 1{
                    
                    let pageNum = fileItem.objectForKey("page_number") as! Int
                    let quantity = fileItem.objectForKey("goods_number") as! Int
                    
                    infoLabel.text = "\(pageNum)页 x \(quantity)份"
                    
                    let bwOption = fileItem.objectForKey("black_white_color") as! Int
                    let duplex = fileItem.objectForKey("single_double") as! Int
                    
                    
                    
                    if duplex == 1 && bwOption == 1{
                        infoLabel.text! += " 单面 黑白"
                        var single: Double?
                        let singleStr = pricesTabel.objectForKey("1")
                        if singleStr != nil{
                            single = Double(singleStr as! String)
                        }
                        if single != nil{
                            priceLabel.text = "￥ \(String(format: "%.2lf", Double(pageNum*quantity)*single!))"
                        }else{
                            priceLabel.text = "商家不支持"
                        }
                    }else if duplex == 1 && bwOption == 2{
                        infoLabel.text! += " 单面 彩色"
                        var single: Double?
                        let singleStr = pricesTabel.objectForKey("3")
                        if singleStr != nil{
                            single = Double(singleStr as! String)
                        }
                        if single != nil{
                            priceLabel.text = "￥ \(String(format: "%.2lf", Double(pageNum*quantity)*single!))"
                        }else{
                            priceLabel.text = "商家不支持"
                        }
                    }else if duplex == 2 && bwOption == 1{
                        infoLabel.text! += " 双面 黑白"
                        var single: Double?
                        let singleStr = pricesTabel.objectForKey("2")
                        if singleStr != nil{
                            single = Double(singleStr as! String)
                        }
                        if single != nil{
                            priceLabel.text = "￥ \(String(format: "%.2lf", Double(pageNum*quantity)*single!))"
                        }else{
                            priceLabel.text = "商家不支持"
                        }
                    }else if duplex == 2 && bwOption == 2{
                        infoLabel.text! += " 双面 彩色"
                        var single: Double?
                        let singleStr = pricesTabel.objectForKey("4")
                        if singleStr != nil{
                            single = Double(singleStr as! String)
                        }
                        if single != nil{
                            priceLabel.text = "￥ \(String(format: "%.2lf", Double(pageNum*quantity)*single!))"
                        }else{
                            priceLabel.text = "商家不支持"
                        }
                    }
                    
                    infoLabel.center.x += 16
                    
                }
                
                
                
            }else{
                if indexPath.row == fileInfos!.count*2 {
                    infoLabel.text = "某种优惠"
                    priceLabel.text = "- ￥ 0"
                    
                    
                }else if indexPath.row == fileInfos!.count*2 + 1{
                    infoLabel.text = "某种优惠"
                    // TODO: cutOff
                    priceLabel.text = "- ￥ 0"
                }
                
            }
            break
        default:
            break
        }
        
        
        return cell
    }
    
    func nextStep(){
        
        if nameInput.text == "" {
            let alert = UIAlertController(title: "请填写您的姓名", message: nil, preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: { (action) in
                self.nameInput.becomeFirstResponder()
            }))
            presentViewController(alert, animated: true, completion: nil)
            return
        }
        
        if phoneInput.text == "" {
            let alert = UIAlertController(title: "请填写您的联系电话", message: nil, preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: { (action) in
                self.phoneInput.becomeFirstResponder()
            }))
            presentViewController(alert, animated: true, completion: nil)
            return
        }
        
        if Int(totalPrice*100) != 0{
            print("在此进行提交订单操作")
            spinner.alpha = 1
            submitBtn.enabled = false
            submitBtn.backgroundColor = UIColor.grayColor()
            
            let jsonDic = NSMutableDictionary()
            jsonDic.setValue("alipay", forKey: "payMethod")
            
            let shop = shopInfos.objectAtIndex(0) as! NSDictionary
            var bid = shop.objectForKey("id") as? Int
            if bid == nil{
                bid = Int(shop.objectForKey("id") as! String)
            }
            if bid != nil{
                jsonDic.setValue(bid!, forKey: "bid")
            }
            
            
            if commentInput.text != nil {
                jsonDic.setValue(commentInput.text!, forKey: "remark")
            }
            
            jsonDic.setValue(String(format: "%.2lf", totalPrice), forKey: "totalPrice")
            
            jsonDic.setValue(nameInput.text!, forKey: "name")
            jsonDic.setValue(phoneInput.text!, forKey: "phone")
            NSUserDefaults.standardUserDefaults().setValue(nameInput.text!, forKey: "info_name")
            NSUserDefaults.standardUserDefaults().setValue(phoneInput.text!, forKey: "info_phone")
            
            let files = NSMutableArray()
            for f in fileInfos{
                let fileJson = NSMutableDictionary()
                let fileItem = f as! NSDictionary
                let quantity = fileItem.objectForKey("goods_number") as! Int
                
                let bwOption = fileItem.objectForKey("black_white_color") as! Int
                let duplex = fileItem.objectForKey("single_double") as! Int
                
                let fileID = fileItem.objectForKey("file_id") as! String
                
                fileJson.setValue(fileID, forKey: "file_id")
                fileJson.setValue(quantity, forKey: "goods_number")
                fileJson.setValue(bwOption, forKey: "paper_type")
                fileJson.setValue(duplex, forKey: "single_double")
                files.addObject(fileJson)
            }
            
            jsonDic.setValue(files, forKey: "fileInfos")
            
            let jsonData = try? NSJSONSerialization.dataWithJSONObject(jsonDic, options: .PrettyPrinted)
            if jsonData != nil {
                print(String(data: jsonData!, encoding: NSUTF8StringEncoding))
                let postResq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
                postResq.HTTPMethod = "POST"
                let postData = NSMutableData()
                postData.appendData(NSString(string: "act=submitOrder&json=").dataUsingEncoding(NSUTF8StringEncoding)!)
                postData.appendData(jsonData!)
                postResq.HTTPBody = postData
                
                NSURLSession.sharedSession().dataTaskWithRequest(postResq, completionHandler: { (data:NSData?, resq:NSURLResponse?, err:NSError?) in
                    var failed = true
                    var errMsg: String?
                    if err == nil {
                        if data != nil{
                            print(String(data: data!, encoding: NSUTF8StringEncoding))
                            let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                            if jsonObj != nil{
                                let jsonDic = jsonObj as! NSDictionary
                                let reCode = jsonDic.objectForKey("code") as? Int
                                if reCode == 200{
                                    failed = false
                                    NSUserDefaults.standardUserDefaults().setObject(true, forKey: "orderListRefreshRequire")
                                    dispatch_async(dispatch_get_main_queue(), {
                                        let payVC = PayViewController(amount: self.totalPrice)
                                        payVC.delegate = self
                                        self.presentViewController(payVC, animated: true, completion: nil)
                                        
                                    })
                                }else{
                                    errMsg = jsonDic.objectForKey("message") as? String
                                }
                            }
                        }
                    }
                    
                    if failed{
                        dispatch_async(dispatch_get_main_queue(), {
                            self.spinner.alpha = 0
                            self.submitBtn.enabled = true
                            self.submitBtn.backgroundColor = UIColor.orangeColor()
                            UIAlertView(title: "提交失败", message: errMsg, delegate: nil, cancelButtonTitle: "OK").show()
                        })
                    }
                    
                }).resume()
            }
            
            /*
            //TODO: 写死计时演示
            if #available(iOS 10.0, *) {
                NSTimer.scheduledTimerWithTimeInterval(1, repeats: false) { (timer) in
                    
                    let payVC = PayViewController(amount: 1.0)
                    payVC.delegate = self
                    self.presentViewController(payVC, animated: true, completion: nil)
                }
            } else {
                let payVC = PayViewController(amount: 1.0)
                payVC.delegate = self
                self.presentViewController(payVC, animated: true, completion: nil)
            }
            */
        }else{
            let hintToast = UILabel(frame: CGRect(x: 32, y: view.bounds.height - 112, width: view.bounds.width-64, height: 48))
            hintToast.backgroundColor = UIColor(white: 0, alpha: 0.6)
            hintToast.layer.cornerRadius = 8
            hintToast.layer.masksToBounds = true
            hintToast.text = "存在商家不支持的商品，请返回上一步，选择其他商家，或者调整商品属性。"
            hintToast.numberOfLines = 2
            hintToast.font = UIFont.systemFontOfSize(14)
            hintToast.textColor = UIColor.whiteColor()
            view.addSubview(hintToast)
            
            hintToast.alpha = 0
            UIView.animateWithDuration(0.3, animations: {
                hintToast.alpha = 1
                }, completion: { (finished) in
                    UIView.animateWithDuration(0.3, delay: 2, options: .CurveLinear, animations: {
                        hintToast.alpha = 0
                        }, completion: nil)
            })
        }
        
        
    }
    
    func didFinishedPay(result: Bool) {
        if step0VC != nil{
            navigationController?.popToViewController(step0VC!, animated: true)
        }else{
            navigationController?.popToRootViewControllerAnimated(true)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func textFieldScrollUp(textField: UITextField) {
        // MARK: 输入框被键盘遮盖时往上移动
        if textField.tag == commentInput.tag{
            var height = 124 + shopDescriptionHeight
            
            height = height - view.bounds.height/2 + 128
            if tableView.contentOffset.y < height{
                tableView.setContentOffset(CGPoint(x: 0, y: height), animated: true)
            }
        }else if textField.tag == phoneInput.tag || textField.tag == nameInput.tag {
            var height = 108 + shopDescriptionHeight
            
            height = height - view.bounds.height/2 + 128
            if tableView.contentOffset.y < height{
                tableView.setContentOffset(CGPoint(x: 0, y: height), animated: true)
            }
        }
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
